const response = require('../utils/response');

const validationMiddleware = (rulesSchema, type = 'body') => {
    return async function (ctx, next) {
        try {
            let input = type === 'body' ? ctx.request.body : ctx.request.query;
            let schema = rulesSchema[ctx.path];
            if (!schema) {
                return response.error(ctx, { message: '使用但未配置参数rulesSchema' });
            }
            const { error } = schema.validate(input, { abortEarly: false, allowUnknown: true });

            if (error) {
                const errorMessage = error.details.map(detail => detail.message).join(', ');
                return response.error(ctx, { message: errorMessage });
            }
            await next();
        } catch (err) {
            console.log(err);
            response.error(ctx, { message: '服务验证错误' });
        }
    };
};

module.exports = validationMiddleware;
